<?php
class lib_base extends Model
{
    public $table_name = '';
    public $pk = '';
    public $token = '';
    public $cacheTime = 86400;
    public $orderby = array();




    //添加
    public function add($data)
    {
        return $this->create($data);
    }
    //编辑
    public function edit($id,$data)
    {
        return $this->update(array("{$this->pk}"=>$id), $data);
    }
    //删除回收
    public function del($doids,$recycle=0)
    {
        if($recycle = 1){
            return $this->act($doids,-1);
        }else{
            return $this->delete(array("{$this->pk} IN ({$doids})"));
        }
    }
    //显示隐藏
    public function act($doids,$status,$field='status')
    {
        return $this->update(array("{$this->pk} IN ({$doids})"),array($field=>$status));
    }
    //排序
    public function sort($data)
    {
        foreach ($data as $key => $val) {
            $arrBase = array(
                'sort' => $val,
            );
            $this->update(array("{$this->pk}"=>$key), $arrBase);
        }
        return true;
    }
    //获取单条记录
    public function get_info($cond,$sort=null,$fields='*')
    {
        if(is_numeric($cond)){
            $cond = array("{$this->pk}"=>"{$cond}");
        }elseif(!is_array($cond)){
            $cond = array($cond);
            // dump($cond);
        }else{
            $cond = $cond;
        }
        if(!$sort) $sort = "{$this->pk} desc";
        return $this->find($cond,$sort,$fields);
    }
     //获取单条记录
     public function get_pinfo($cond)
    {
        $info = $this->get_info($cond);
        $pinfo = $this->get_info($info['parent_id']);
        return $pinfo;
    }
    //获取全部记录
    public function get_list($cond,$sort=null,$fields='*')
    {
        if(is_numeric($cond)){
            $cond = array("{$this->pk}"=>"{$cond}");
        }
        if(!is_array($cond)){
            $cond = array($cond);
        }
        if(!$sort) $sort = "{$this->pk} asc";
        return $this->findAll($cond,$sort,$fields);
    }
    //获取多条记录page
    public function get_pagelist($cond='',$sort=null,$fields='*',$limit=20)
    {
        $data = [];

        if(!$sort) $sort = "{$this->pk} desc";
        if(!$cond) $cond = "1=1";
        $page = (int)arg("page", 1);
        $result = $this->findAll(array($cond),$sort,$fields,array($page, $limit));
        if($result){
            foreach ($result as $key => $val) {
                // $val['add_time'] = date('Y-m-d H:i:s',$val['add_time']);
                $list[] = $val;
            }
            $pager = $this->page;

            if(!$pager){
                $pager['total_count'] = count($list);
            }
            $showPage = html_showPage1($pager);

            $data['list'] = $list;
            // $data['page'] = $pager;
            $data['total'] = $pager['total_count'];
            $data['showPage'] = $showPage;
        }else{
            $data['list'] = [];
            $data['total'] = 0;
        }
        return $data;
    }

    //下拉刷新
    public function get_loaddata($cond,$sort=null,$fields='*',$limit=10)
    {
        if(!$sort) $sort = "{$this->pk} desc";
        $page = (int)arg("page", 1);

        $result = $this->findAll(array($cond), $sort, $fields, array($page, $limit));
        if($result){
            foreach ($result as $key => $val) {
                $val['addtime'] = date('Y-m-d',strtotime($val['add_time']));
                $list[] = $val;
            }
            $pager = $this->page;
            if($pager){
                $total = $pager['total_page'];
                if($total < $page ) {
                    return false;
                }
            }else{
                $total = count($list);
                if($page>1) {
                    return false;
                }
            }
            $data['list'] = $list;
            $data['total'] = $total;
        }else{
            $data['list'] = [];
            $data['total'] = 0;
        }
        return $data;
    }

    public function get_childList($cond,$sort='sort asc,id desc')
    {
        $all = $this->findAll(array($cond),$sort);
        $all = formatChildData($all);
        return $all;
    }

    public function get_treeList($cond,$sort='sort asc,id desc')
    {
        $all = $this->findAll(array($cond),$sort);
        $all = formatTreeData($all);
        return $all;
    }


    //js 树形列表
    public function get_JsTree($cond,$access_ids='',$field='name',$js_data=[])
    {
        // $accessIds = is_null($role_id) ? [] : D('company_role')::getAccessIds($role_id);
        // dump($access_ids);exit;
        if($access_ids){
            $access_ids = explode(',',$access_ids);
        }
        $jsTree = [];
        $data = $this->findAll(array($cond));
        if($js_data){
            $data = array_merge($data,[$js_data]);
        }
        foreach ($data as $item) {
            $jsTree[] = [
                'id' => $item['id'],
                'parent' => $item['parent_id'] > 0 ? $item['parent_id'] : '#',
                'text' => $item[$field],
                'auth' => in_array($item['id'], $access_ids) && !$this->hasChildren($cond,$item['id']),
                'state' => [
                    'selected' => (in_array($item['id'], $access_ids) && !$this->hasChildren($cond,$item['id']))
                ]
            ];
        }

        return json_encode($jsTree);
    }

    private function hasChildren($cond,$access_id)
    {
        $data = $this->findAll(array($cond));
        foreach ($data as $item) {
            if ($item['parent_id'] == $access_id)
                return true;
        }
        return false;
    }




    //缓存查询所有记录pk主键
    public function fetchAll($cond = '', $sort = null, $fields = '*', $limit = null){
        // $cache = S(array('type'=>'File','expire'=>  $this->cacheTime));
        // if(!$data= S($this->token)){
            $result = $this->findAll($cond, $sort, $fields, $limit);
            foreach($result  as $val){
                $data[$val[$this->pk]] = $val;
            }
            // S($this->token,$data);
        // }
        return $data;
    }





    //根据ID查询
    public function get_id($id,$sort=null,$fields='*')
    {
        if(!$sort) $sort = "{$this->pk} desc";
        return $this->find(array("{$this->pk}"=>"{$id}"),$sort,$fields);
    }
    //根据ID查询数据
    public function get_ids($ids = array(), $cond ='', $sort = null ,$fields='*')
    {
        if(empty($ids)) return array();
        if(is_array($ids)) $ids = implode(',', $ids);
        $cond = "{$this->pk} IN ({$ids}) ".$cond;
        $result = $this->findAll(array($cond), $sort, $fields);
        $data = array();
        foreach($result as $val){
            if($val['parent_id']){
                $val['pinfo'] = $this->findById($val['parent_id']);
            }
            $data[$val[$this->pk]] = $val;
        }
        return $data;
    }
    //获取IDS
    public function ids($arr,$field,$fields='*')
    {
        foreach ($arr as $val) {
            if($val[$field]) $arr_ids[$val[$field]] = $val[$field];
        }
        if($arr_ids){
            return $this->get_ids($arr_ids,'','',$fields);
        }

    }




    ///////////////////////////
    //根据PK查询
    public function findById($id,$fields='*'){
        $data = $this->find(array("{$this->pk}"=>"{$id}"),'',$fields);
        return $data;
    }
    //根据ID查询数据
    public function findByIds($ids = array(), $cond='', $sort = null,$fields='*'){
        if(empty($ids)) return array();
        if(is_array($ids)) $ids = implode(',', $ids);
        $cond = "{$this->pk} IN ({$ids}) ".$cond;
        $data = $this->findAll(array($cond), $sort, $fields);
        $return = array();
        foreach($data as $val){
            $return[$val[$this->pk]] = $val;
        }
        return $return;
    }

    public function findAllByPk($cond = '', $sort = null, $fields = '*', $limit = null){
        // $cache = S(array('type'=>'File','expire'=>  $this->cacheTime));
        // if(!$data= S($this->token)){
            $result = $this->findAll($cond, $sort, $fields, $limit);
            foreach($result  as $val){
                $data[$val[$this->pk]] = $val;
            }
            // S($this->token,$data);
        // }
        return $data;
    }

    public function findSql($cond){
        return $this->query('SELECT * FROM '.$this->table_name.' WHERE '.$cond);
    }
    public function updateSql($cond,$arrBase){
        return $this->query('UPDATE '.$this->table_name.' SET '.$arrBase.' WHERE '.$cond);
    }
    //事务开关
    public function Autocommit_off(){
        $this->query('SET AUTOCOMMIT=1');
    }
    public function Autocommit_no(){
        $this->query('SET AUTOCOMMIT=0');
    }
    //开启事务
    public function Autocommit_start(){
        $this->query('START TRANSACTION');
        $this->Autocommit = 'start';
    }
    //成功执行
    public function Autocommit_commit(){
        $this->query('COMMIT');
        $this->Autocommit = 'commit';
    }
    //回滚事务
    public function Autocommit_rollback(){
        $this->query('ROLLBACK');
        $this->Autocommit = 'rollback';
    }

}